<template>
  <div class="news-page">
    <NavBar />
    
    <!-- 页面标题 -->
    <section class="page-header relative overflow-hidden py-20 bg-gradient-to-r from-blue-600 via-blue-500 to-indigo-600 text-white">
      <!-- 网格装饰 -->
      <div class="absolute inset-0 bg-[linear-gradient(to_right,#ffffff0d_1px,transparent_1px),linear-gradient(to_bottom,#ffffff0d_1px,transparent_1px)] bg-[size:24px_24px]"></div>
      
      <!-- 装饰元素 -->
      <div class="absolute top-0 left-0 w-full h-full overflow-hidden opacity-20">
        <div class="absolute -top-10 -left-10 w-40 h-40 rounded-full bg-white blur-3xl"></div>
        <div class="absolute bottom-10 right-10 w-60 h-60 rounded-full bg-white blur-3xl"></div>
        
        <!-- 缓慢脉冲动画装饰 -->
        <div class="absolute top-1/4 right-1/3 w-32 h-32 rounded-full bg-blue-300 blur-3xl animate-slow-pulse opacity-20"></div>
        <div class="absolute bottom-1/3 left-1/4 w-40 h-40 rounded-full bg-indigo-300 blur-3xl animate-slow-pulse opacity-20" style="animation-delay: 1s;"></div>
      </div>
      <div class="container mx-auto px-4 text-center relative z-10">
        <h1 class="text-[clamp(2.5rem,5vw,4rem)] font-bold mb-4 tracking-tight animate-fade-in-up">
          {{ $t('nav.news') }}
        </h1>
        <p class="text-[clamp(1rem,2vw,1.5rem)] max-w-2xl mx-auto opacity-90 animate-fade-in-up delay-100">
          行业动态与公司新闻
        </p>
        <!-- 滚动指示 -->
        <div class="mt-8 animate-bounce">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 mx-auto opacity-80" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3" />
          </svg>
        </div>
      </div>
    </section>

    <!-- 新闻列表 -->
    <section class="news-list py-16 bg-gradient-to-b from-white via-blue-50/20 to-white" ref="newsListRef">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-8">
          <!-- 左侧边栏 -->
          <div class="md:col-span-1 order-2 md:order-1">
            <div class="sidebar bg-white rounded-xl shadow-md p-6 mb-8 opacity-0 transform translate-y-8 transition-all duration-700 relative overflow-hidden">
              <!-- 装饰元素 -->
              <div class="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-blue-50 to-indigo-50 rounded-bl-full -z-10"></div>
              <div class="flex items-center mb-6">
                <div class="w-2 h-8 bg-blue-600 rounded-full mr-3"></div>
                <h3 class="text-xl font-bold">新闻分类</h3>
              </div>
              <ul class="space-y-3">
                <li>
                  <button 
                    :class="[
                      'category-btn w-full text-left px-4 py-3 rounded-lg transition-all duration-300 flex items-center',
                      activeCategory === 0 
                        ? 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md' 
                        : 'hover:bg-gray-50 hover:shadow-sm'
                    ]"
                    @click="activeCategory = 0"
                  >
                    <svg v-if="activeCategory === 0" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                    </svg>
                    <span v-else class="w-4 mr-2"></span>
                    全部新闻
                  </button>
                </li>
                <li v-for="category in categories" :key="category.id">
                  <button 
                    :class="[
                      'category-btn w-full text-left px-4 py-3 rounded-lg transition-all duration-300 flex items-center',
                      activeCategory === category.id 
                        ? 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md' 
                        : 'hover:bg-gray-50 hover:shadow-sm'
                    ]"
                    @click="activeCategory = category.id"
                  >
                    <svg v-if="activeCategory === category.id" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                    </svg>
                    <span v-else class="w-4 mr-2"></span>
                    {{ category.name }}
                  </button>
                </li>
              </ul>
            </div>
            
            <div class="sidebar bg-white rounded-xl shadow-md p-6 opacity-0 transform translate-y-8 transition-all duration-700 delay-200 relative overflow-hidden">
              <!-- 装饰元素 -->
              <div class="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-blue-50 to-indigo-50 rounded-bl-full -z-10"></div>
              <div class="flex items-center mb-6">
                <div class="w-2 h-8 bg-blue-600 rounded-full mr-3"></div>
                <h3 class="text-xl font-bold">热门新闻</h3>
              </div>
              <ul class="space-y-4">
                <li v-for="(news, index) in hotNews" :key="news.id">
                  <router-link 
                    :to="'/news/' + news.id"
                    class="flex group p-2 rounded-lg transition-all duration-700 transform hover:-translate-y-1 hover:bg-blue-50 hover:shadow-md"
                  >
                    <div 
                      class="w-24 h-24 flex-shrink-0 mr-3 rounded-lg overflow-hidden relative"
                      :style="{ 
                        backgroundImage: `url(${news.image || ''})`,
                        backgroundSize: 'cover',
                        backgroundPosition: 'center',
                        backgroundRepeat: 'no-repeat',
                        backgroundColor: news.image ? 'transparent' : '#e0e7ff'
                      }"
                    >
                      <div v-if="!news.image" class="absolute inset-0 flex items-center justify-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-blue-600 opacity-50" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                        </svg>
                      </div>
                    </div>
                    <div class="flex-grow">
                      <h4 class="font-medium text-gray-800 group-hover:text-blue-600 transition-colors line-clamp-2">{{ news.title }}</h4>
                      <p class="text-sm text-gray-500 mt-1">{{ formatDate(news.date) }}</p>
                    </div>
                  </router-link>
                </li>
              </ul>
            </div>
          </div>
          
          <!-- 右侧新闻列表 -->
          <div class="md:col-span-2 order-1 md:order-2">
            <div 
              v-for="(news, index) in displayNews" 
              :key="news.id"
              class="news-card bg-white rounded-xl shadow-md mb-8 overflow-hidden transform transition-all duration-700 hover:shadow-xl hover:-translate-y-1 opacity-0 relative"
                 :style="{ borderTop: '4px solid ' + getCategoryColor(news.categoryId) }"
              :ref="el => newsCardRefs[index] = el as HTMLElement"
            >
              <div class="md:flex">
                <div 
                  class="md:w-1/3 news-image h-60 md:h-auto relative overflow-hidden"
                  :style="{ 
                    backgroundImage: `url(${news.image || ''})`,
                    backgroundSize: 'cover',
                    backgroundPosition: 'center',
                    backgroundRepeat: 'no-repeat',
                    backgroundColor: news.image ? 'transparent' : '#e0e7ff'
                  }"
                >
                  <div v-if="!news.image" class="absolute inset-0 flex items-center justify-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-blue-600 opacity-30" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                  </div>
                </div>
                <div class="md:w-2/3 p-6">
                  <div class="flex items-center mb-4">
                    <span :class="['px-3 py-1 rounded-full text-xs font-medium mr-3', getCategoryBadgeClass(news.categoryId)]">{{ news.categoryName }}</span>
                    <span class="text-gray-500 text-sm">{{ formatDate(news.date) }}</span>
                  </div>
                  <h3 class="text-2xl font-bold mb-4 text-gray-800 transition-colors hover:text-blue-600">{{ news.title }}</h3>
                  <p class="text-gray-600 mb-6 line-clamp-3 leading-relaxed">{{ news.summary }}</p>
                  <router-link 
                    :to="'/news/' + news.id" 
                    class="inline-flex items-center text-blue-600 font-medium hover:text-indigo-600 transition-colors group"
                  >
                    <span>阅读更多</span>
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-2 transform group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3" />
                    </svg>
                  </router-link>
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="mt-12 flex justify-center opacity-0 transform translate-y-8 transition-all duration-700 delay-300" ref="paginationRef" v-if="totalPages > 1">
              <div class="pagination-container">
                <!-- 上一页 -->
                <button 
                  @click="goToPrevPage" 
                  :disabled="currentPage === 1" 
                  class="pagination-btn pagination-btn-prev"
                  :class="{ 'disabled': currentPage === 1 }">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
                  </svg>
                </button>
                <!-- 页码按钮 -->
                <div class="pagination-pages">
                  <button v-for="page in pageNumbers" :key="page" @click="goToPage(page)" class="pagination-page" :class="{ 'active': page === currentPage }">
                    {{ page }}
                  </button>
                </div>
                <!-- 下一页 -->
                <button 
                  @click="goToNextPage" 
                  :disabled="currentPage === totalPages"
                  class="pagination-btn pagination-btn-next" 
                  :class="{ 'disabled': currentPage === totalPages }">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
                  </svg>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import NavBar from '@/components/NavBar.vue'
import Footer from '@/components/Footer.vue'
import { ElPagination } from 'element-plus'
import { news as newsData } from '@/data/news'

// 新闻分类数据
const categories = [
  { id: 1, name: '公司新闻' },
  { id: 2, name: '行业资讯' },
  { id: 3, name: '技术动态' },
  { id: 4, name: '产品发布' }
]

// 新闻数据（抽取到独立数据文件，按id顺序排序）
const news = [...newsData].sort((a, b) => a.id - b.id)

// 响应式数据
const activeCategory = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

// 计算属性：过滤后的新闻列表（保持id顺序）
const filteredNews = computed(() => {
  let result = news
  if (activeCategory.value !== 0) {
    result = news.filter(item => item.categoryId === activeCategory.value)
  }
  // 确保按id顺序排序
  return result.sort((a, b) => a.id - b.id)
})

// 热门新闻
const hotNews = computed(() => {
  return news.filter(item => item.isHot).slice(0, 5)
})

// 分页相关计算
const total = computed(() => filteredNews.value.length)
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
const displayNews = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = currentPage.value * pageSize.value
  return filteredNews.value.slice(start, end)
})
const pageNumbers = computed(() => {
  const pages: (number | string)[] = []
  const maxPages = 5
  if (totalPages.value <= maxPages) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i)
    }
  } else {
    if (currentPage.value <= 3) {
      for (let i = 1; i <= 4; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(totalPages.value)
    } else if (currentPage.value >= totalPages.value - 2) {
      pages.push(1)
      pages.push('...')
      for (let i = totalPages.value - 3; i <= totalPages.value; i++) {
        pages.push(i)
      }
    } else {
      pages.push(1)
      pages.push('...')
      for (let i = currentPage.value - 1; i <= currentPage.value + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(totalPages.value)
    }
  }
  return pages
})
const goToPage = (page: number | string) => {
  if (page === '...') return
  const pageNum = typeof page === 'number' ? page : parseInt(page)
  if (pageNum !== currentPage.value && pageNum >= 1 && pageNum <= totalPages.value) {
    currentPage.value = pageNum
    setTimeout(() => handleScroll(), 100)
  }
}
const goToPrevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    setTimeout(() => handleScroll(), 100)
  }
}
const goToNextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    setTimeout(() => handleScroll(), 100)
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}.${month}.${day}`
}

// 获取分类对应的颜色
const getCategoryColor = (categoryId: number) => {
  const colorMap: Record<number, string> = {
    1: '#409eff', // 公司新闻 - 蓝色
    2: '#67c23a', // 行业资讯 - 绿色
    3: '#e6a23c', // 技术动态 - 黄色
    4: '#f56c6c'  // 产品发布 - 红色
  }
  return colorMap[categoryId] || '#409eff'
}

// 获取分类标签样式
const getCategoryBadgeClass = (categoryId: number) => {
  const badgeMap: Record<number, string> = {
    1: 'bg-gradient-to-r from-blue-100 to-blue-200 text-blue-700',
    2: 'bg-gradient-to-r from-green-100 to-green-200 text-green-700',
    3: 'bg-gradient-to-r from-yellow-100 to-yellow-200 text-yellow-700',
    4: 'bg-gradient-to-r from-red-100 to-red-200 text-red-700'
  }
  return badgeMap[categoryId] || 'bg-gradient-to-r from-blue-100 to-indigo-100 text-blue-700'
}

// 滚动动画相关
const newsListRef = ref<HTMLElement>()
const newsCardRefs = ref<HTMLElement[]>([])
const paginationRef = ref<HTMLElement>()
const animatedElements = ref<HTMLElement[]>([])

// 检测元素是否在视口中
const isInViewport = (element: HTMLElement) => {
  const rect = element.getBoundingClientRect()
  return (
    rect.top <= window.innerHeight * 0.8 &&
    rect.bottom >= 0
  )
}

// 处理滚动事件，添加动画效果
const handleScroll = () => {
  // 添加延迟动画到新闻卡片
  newsCardRefs.value.forEach((card, index) => {
    if (card && isInViewport(card)) {
      window.setTimeout(() => {
        card.style.opacity = '1'
        card.style.transform = 'translateY(0)'
        card.style.transitionDelay = `${index * 0.1}s`
      }, 100)
    }
  })
  
  // 侧边栏动画
  if (newsListRef.value) {
    const sidebars = newsListRef.value.querySelectorAll('.sidebar')
    sidebars.forEach((sidebar, index) => {
      if (isInViewport(sidebar as HTMLElement)) {
        window.setTimeout(() => {
          (sidebar as HTMLElement).style.opacity = '1';
          (sidebar as HTMLElement).style.transform = 'translateY(0)';
        }, 100 + index * 200)
      }
    })
  }
  
  // 分页组件动画
  if (paginationRef.value && isInViewport(paginationRef.value)) {
    paginationRef.value.style.opacity = '1'
    paginationRef.value.style.transform = 'translateY(0)'
  }
}

// 监听分类变化，重新触发动画
watch(activeCategory, () => {
  window.setTimeout(() => {
    handleScroll()
  }, 100)
})

onMounted(() => {
  // 初始化新闻卡片样式
  newsCardRefs.value.forEach((card, index) => {
    if (card) {
      card.style.transition = 'opacity 0.7s ease, transform 0.7s ease'
      card.style.transform = 'translateY(20px)'
    }
  })
  
  window.addEventListener('scroll', handleScroll)
  // 初始检查一次，确保页面加载时可见的元素也能触发动画
  setTimeout(handleScroll, 100)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.news-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 分页组件样式优化 */
:deep(.custom-pagination .el-pagination__sizes .el-input .el-input__wrapper) {
  border-radius: 6px;
}

:deep(.custom-pagination .el-pager li) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.custom-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #409eff, #667eea);
  border-color: transparent;
}

:deep(.custom-pagination .el-pager li:not(.is-active):hover) {
  background-color: #f0f9ff;
  color: #409eff;
}

/* 动画类 */
.animate-fade-in-up {
  animation: fadeInUp 0.8s ease forwards;
}

.animate-bounce {
  animation: bounce 2s infinite;
}

.animate-slow-pulse {
  animation: slowPulse 4s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

.delay-100 {
  animation-delay: 0.1s;
}

.delay-200 {
  animation-delay: 0.2s;
}

.delay-300 {
  animation-delay: 0.3s;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounce {
  0%, 20%, 53%, 80%, 100% {
    animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
    transform: translate3d(0, 0, 0);
  }
  40%, 43% {
    animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
    transform: translate3d(0, -8px, 0);
  }
  70% {
    animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
    transform: translate3d(0, -4px, 0);
  }
  90% {
    transform: translate3d(0, -2px, 0);
  }
}

@keyframes slowPulse {
  0%, 100% {
    opacity: 0.1;
    transform: scale(1);
  }
  50% {
    opacity: 0.2;
    transform: scale(1.1);
  }
}

.pagination-container {
  display: flex;
  align-items: center;
  gap: 8px;
}
.pagination-btn {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
  padding: 0;
}
.pagination-btn:hover:not(.disabled) {
  color: #3b82f6;
  border-color: #3b82f6;
  background: #ecf5ff;
}
.pagination-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.pagination-pages {
  display: flex;
  align-items: center;
  gap: 8px;
}
.pagination-page {
  min-width: 36px;
  height: 36px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  font-weight: 500;
}
.pagination-page:hover {
  color: #3b82f6;
  border-color: #3b82f6;
  background: #ecf5ff;
}
.pagination-page.active {
  background: #3b82f6;
  border-color: #3b82f6;
  color: #ffffff;
  font-weight: 600;
}
.pagination-page.active:hover {
  background: #2563eb;
  border-color: #2563eb;
}
</style>